package ucuserslogic

import (
	"context"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/usercenter"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"

	"navi-mumbai/app/rpc/usercenter/internal/svc"
	"navi-mumbai/app/rpc/usercenter/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateProfileLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateProfileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateProfileLogic {
	return &UpdateProfileLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 更新个人资料
func (l *UpdateProfileLogic) UpdateProfile(in *pb.UpdateProfileReq) (*pb.UpdateProfileResp, error) {
	defer utils.RecoverPanic()

	var err error
	var up *usercenter.UserProfile
	up, err = l.svcCtx.UserProfileModel.FindOne(l.ctx, in.Uid)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}

	if in.Email != "" {
		up.Email = in.Email
	}
	if in.Avatar != "" {
		up.Avatar = in.Avatar
	}
	if in.Language != 0 {
		up.Language = in.Language
	}

	err = l.svcCtx.UserProfileModel.Update(l.ctx, up)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	var rsp pb.UpdateProfileResp
	rsp.Profile = &pb.UserProfile{
		Email:    up.Email,
		Avatar:   up.Avatar,
		Language: up.Language,
		AreaNo:   up.AreaNo,
		PhoneNo:  up.PhoneNo,
	}
	return &rsp, nil
}
